package com.myapplication.zhou.alldemo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.BitmapRequestBuilder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.model.GlideUrl;
import com.google.gson.Gson;
import com.myapplication.callback.AddInCartCallback;
import com.myapplication.callback.GoodsInfoCallback;
import com.myapplication.helper.PreferencesHelper;
import com.myapplication.helper.PreferencesHelper1;
import com.myapplication.interfaces.AddInCartConnect;
import com.myapplication.interfaces.GoodsInfoConnect;
import com.myapplication.model.GoodsCommend;
import com.myapplication.model.GoodsInfo;
import com.myapplication.model.UserInfo;
import com.myapplication.viewpager.ChangableViewPager;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;

public class GoodsInfoActivity extends AppCompatActivity implements GoodsInfoCallback,
        SwipeRefreshLayout.OnRefreshListener, View.OnClickListener,AddInCartCallback {

    @ViewInject(R.id.toolbar)
    private Toolbar toolbar;
    @ViewInject(R.id.viewPager)
    private ViewPager viewPager;
    @ViewInject(R.id.textView_good_name)
    private TextView textViewGoodName;
    @ViewInject(R.id.textView_price)
    private TextView textViewPrice;
    @ViewInject(R.id.textView_old_price)
    private TextView textViewOldPrice;
    @ViewInject(R.id.textView_zhekou)
    private TextView textViewZhekou;
    @ViewInject(R.id.kuchunliang)
    private TextView textView_kuchuliang;
    @ViewInject(R.id.youfei)
    private TextView textView_youfei;
    private GoodsInfoConnect goodsInfoConnect;
    @ViewInject(R.id.swipeRefresh)
    private SwipeRefreshLayout refreshLayout;
    private String goods_id;
    private Gson gson;
    private GoodsInfo goodsInfo;
    @ViewInject(R.id.nestedScrollView)
    private NestedScrollView nestedScrollView;
    @ViewInject(R.id.textView_title)
    private TextView textView_title;
    private String[] strArray;
    private BitmapRequestBuilder<GlideUrl, Bitmap> requestBuilder;
    private ArrayList<View> pageViews = new ArrayList<>();
    private ChangableViewPager changableViewPager;
    @ViewInject(R.id.textView_shop_cart)
    private TextView textView_shop_cart;
    private AddInCartConnect addInCartConnect;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_info);
        x.view().inject(this);
        gson = new Gson();
        toolbar.setTitle("");
        addInCartConnect = new AddInCartConnect();
        changableViewPager = new ChangableViewPager(pageViews);
        viewPager.setAdapter(changableViewPager);
        viewPager.addOnPageChangeListener(new onPageChangeListener());
        setSupportActionBar(toolbar);
        textView_shop_cart.setOnClickListener(this);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        textView_title.setText("商品详情");
        nestedScrollView.setVisibility(View.GONE);
        goodsInfoConnect = new GoodsInfoConnect();
        refreshLayout.setColorSchemeResources(android.R.color.holo_orange_light, android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_red_light);
        refreshLayout.setOnRefreshListener(this);
        goods_id = getBundle();
        swipeRefreshPost();
        requestBuilder = Glide.with(this)
                .from(GlideUrl.class)
                .asBitmap()
                .dontAnimate()
                .centerCrop()
                .error(R.mipmap.wutu)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (getSh1().equals("success")) {
            UserInfo userInfo = getSh();
            writeSh("0000");
            String key = userInfo.getKey();
            addInCartConnect.addInCart(goods_id,"1",key,this);
        }

    }

    /**
     * 点击事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textView_shop_cart:
                if (getSh() == null) {
                    writeSh("GoodsInfo");
                    Intent intent = new Intent();
                    intent.setClass(this, LoginActivity.class);
                    startActivity(intent);
                }else {
                    UserInfo userInfo = getSh();
                    String key = userInfo.getKey();
                    addInCartConnect.addInCart(goods_id,"1",key,this);
                }
                break;
        }
    }

    //GoodsInfo
    private void writeSh(String value) {
        PreferencesHelper1.setSharedValue(this, "Login", "Tag", value);
    }

    private String getSh1() {
        return PreferencesHelper1.getSharedValue(this, "Login", "Tag");
    }

    private UserInfo getSh() {
        return PreferencesHelper.getUserInfo(this);
    }

    /**添加至购物车*/
    @Override
    public void onAddInCartSuccess(String success) {
        Log.e(">>>>>>addCart",success);
        try {
            JSONObject jsonObject = new JSONObject(success);
            if(success.contains("login")){
                JSONObject jsonObject1 = jsonObject.optJSONObject("datas");
                String error = jsonObject1.optString("error");
                showSnakeBar(error,R.color.color_red_accent);
            }else {
                String datas = jsonObject.optString("datas");
                if(datas.equals("1")){
                    String info = "已添加至购物车";
                    showSnakeBar(info,R.color.colorAccent);
                }else{
                    String info = "添加失败";
                    showSnakeBar(info,R.color.color_red_accent);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }
    public void showSnakeBar(String info,int color){
        Snackbar snackbar = Snackbar.make(textView_kuchuliang,info,Snackbar.LENGTH_SHORT);
        snackbar.getView().setBackgroundColor(getResources().getColor(color));
        snackbar.show();
    }

    @Override
    public void onAddInCartFail(String fail) {
        Log.e(">>>>>>>addChart",fail);
    }

    class onPageChangeListener implements ViewPager.OnPageChangeListener {
        int a;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {
            a = state;
        }
    }

    public String getBundle() {
        Bundle bundle = getIntent().getExtras();
        return bundle.getString("goods_id");
    }

    public void swipeRefreshPost() {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                onRefresh();
            }
        });
    }

    @Override
    public void onGoodsInfoSuccess(String json) {
        refreshLayout.setRefreshing(false);
        try {
            JSONObject jsonObject = new JSONObject(json);
            String code = jsonObject.optString("code");
            if (code.equals("200")) {
                JSONObject jsonObject1 = jsonObject.optJSONObject("datas");
                JSONObject jsonObject2 = jsonObject1.optJSONObject("goods_info");
                goodsInfo = paraseJsonString(jsonObject2.toString());
                JSONObject jsonObject3 = jsonObject1.optJSONObject("goods_commend_list");
                GoodsCommend goodsCommend = gson.fromJson(jsonObject.toString(), GoodsCommend.class);
                textViewGoodName.setText(goodsInfo.getGoods_name());
                textViewOldPrice.setText("￥" + goodsInfo.getGoods_marketprice());
                textViewPrice.setText("￥" + goodsInfo.getGoods_price());
                textViewZhekou.setText(goodsInfo.getGoods_discount());
                textView_youfei.setText(goodsInfo.getGoods_freight());
                textView_kuchuliang.setText(goodsInfo.getGoods_storage());
                textViewOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                nestedScrollView.setVisibility(View.VISIBLE);
                String goods_image = jsonObject1.optString("goods_image");
                if (goods_image != null) {
                    String[] strArray = goods_image.split(",");
                    Log.i("strarry", strArray.length + "");
                    this.strArray = strArray;

                    for (String s : strArray) {
                        Log.i("sjsj", s);
                        LinearLayout layout = new LinearLayout(this);
                        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.MATCH_PARENT);
                        ImageView imageView = new ImageView(this);
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        requestBuilder.load(new GlideUrl(s)).error(R.mipmap.wutu).into(imageView);
                        layout.addView(imageView, layoutParams);
                        pageViews.add(layout);
                    }
                    changableViewPager.notifyDataSetChanged();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private GoodsInfo paraseJsonString(String json) {
        GoodsInfo goodsInfo = gson.fromJson(json, GoodsInfo.class);
        return goodsInfo;
    }

    @Override
    public void onGoodsInfoFail(String fail) {
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void onRefresh() {
        refreshLayout.setRefreshing(true);
        goodsInfoConnect.getGoodsInfo(goods_id, this);
    }
}
